#include "zmqServer.h"
#include "reaC++.h"
#include "server.h"
#include <QJsonDocument>

namespace rea {

zmqServer::zmqServer(const QJsonObject& aConfig) : QObject()
{
    m_protocal = aConfig.value("protocal").toObject();

    m_sockets.add(rea::Json("rep", rea::Json("type", "router", "ip", "tcp://*:8081"),
                            "pub", rea::Json("type", "pub", "ip", "tcp://*:8080")));

    rea::pipeline::add<QJsonObject>([this](rea::stream<QJsonObject>* aInput){
        ReadMessage(aInput->varData<std::string>("connect"), aInput->data());
    }, rea::Json("name", "serverreceiveZMQ_rep"));

    rea::pipeline::add<clientMessage>([](rea::stream<clientMessage>* aInput){
        auto str = QString(QJsonDocument(aInput->data()).toJson());
        auto scp = std::make_shared<QHash<QString, std::shared_ptr<rea::stream0>>>();
        auto ispub = aInput->tag() == "pub";
        if (!ispub)
            scp->insert("connect", std::make_shared<rea::stream<std::string>>(aInput->varData<std::string>("connect")));
        rea::pipeline::run("serverpostZMQ", rea::Json("id", ispub ? aInput->tag() : "rep", "data", ispub ? rea::JArray("dpst", str) : rea::JArray(str)), "", false, scp);
        aInput->out();
    }, rea::Json("name", "callClient"));

    rea::pipeline::add<clientMessage, rea::pipePartial>([](rea::stream<clientMessage>* aInput){
        aInput->out();
    }, rea::Json("name", "receiveFromClient"));

}

zmqServer::~zmqServer(){

}

void zmqServer::ReadMessage(const std::string& aConnect, const QJsonObject& aData)	//读取信息
{
    auto tp = aData.value("type").toString();
    if (m_protocal.contains(tp))
    {
        clientMessage msg(aData);
        auto scp = std::make_shared<QHash<QString, std::shared_ptr<rea::stream0>>>();
        scp->insert("connect", std::make_shared<rea::stream<std::string>>(aConnect));
        rea::pipeline::run<clientMessage>("receiveFromClient", msg, tp, false, scp);
    }
}

static rea::regPip<QJsonObject> init_server([](rea::stream<QJsonObject>* aInput) {
    static zmqServer sv(aInput->data());
}, rea::Json("name", "createZMQServer"));

//static rea::zmqServer server2();

}
